package
{
	import org.flixel.*;
    
    /**
     * @author Richard Pan
     */
	public class SaveDataManager
	{
        private static var NUM_LEVELS:Number = 20;
        
		private static var _save:FlxSave; //The FlxSave instance
		private static var _loaded:Boolean = false; //Did bind() work? Do we have a valid SharedObject?
        private static var _inkCounts:Array = new Array(NUM_LEVELS);
        //private static var _elapsedTimes:Array = new Array(NUM_LEVELS);
        
		/**
		 * Returns the number of levels that the player has completed
		 */
		public static function saveLevelData(levelNum:Number, inkCount:Number, elapsedTime:Number):void
		{
			if (_loaded) {
                _save.data.inks[levelNum] = inkCount;
            } else {
                _inkCounts[levelNum] = inkCount;
                //_elapsedTimes[levelNum] = elapsedTime;
            }
		}

		/**
		 * Setup LevelsCompleted
		 */
		public static function load(gp:GameProgress):void
		{
            _save = new FlxSave();
			_loaded = _save.bind("myLevelData");
            
            if (_loaded && _save.data.inks == null) {
                _save.data.inks = new Array(NUM_LEVELS);
                for (var i:int = 0; i < NUM_LEVELS; i++ ) {
                    _save.data.inks[i] = -1;
                }
            }
            else if (_loaded && _save.data.inks != null) {
                for (i = 0; i < NUM_LEVELS; i++ ) {
                    if (_save.data.inks[i] != -1) {
                        gp.finishLevel(i, _save.data.inks[i]);
                    } else {
                        break;
                    }
                }
            }
        }
        
        public static function furthestLevel():Number {
            if (_loaded) {
                FlxG.log("Loaded and try to find level");
                for (var i:int = 0; i < NUM_LEVELS; i++ ) {
                    if (_save.data.inks[i] == -1) {
                        FlxG.log("Level " + i);
                        return i;
                    }
                }
                return 0;
            }
            FlxG.log("Not loaded");
            return 0;
        }
	}
}